package com.service.Impl;

import com.entity.Notification;
import com.entity.Post;
import com.entity.User;
import com.exception.GlobalException;
import com.mapper.*;
import com.service.LikeInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ClassName: LikeInfoDaoImpl
 * Description:
 *
 * @author L_Z_R
 * @create 2025/04/16 16:26
 * @version 1.0
 */
@Service
public class LikeInfoServiceImpl implements LikeInfoService {
    @Autowired
    private PostLikeMapper postLikeMapper;
    @Autowired
    private CommentLikeMapper commentLikeMapper;
    @Autowired
    private NotificationMapper notificationMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PostMapper postMapper;
    @Override
    @Transactional
    public void addLike(Integer accountId, Integer postId) {
        try {
            //1. 点赞帖子
            postLikeMapper.addLike(accountId,postId);

            //2. 根据 accountId 查询用户信息
            User user = userMapper.selectUserInfoByAccountId(accountId);

            //3. 根据postId 查询帖子信息
            List<Post> postsByPostId = postMapper.getPostsByPostId(postId);
            Integer receiverId = postsByPostId.get(0).getAccountId();

            Notification notification = new Notification(null,receiverId,"帖子点赞",user.getNickname()+"点赞了您的帖子",(byte) 2,false,null);
            //4. 添加用户点赞通知
            notificationMapper.insert(notification);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(1001,"点赞失败");
        }
    }

    @Override
    public void removeLike(Integer accountId, Integer postId) {
        try {
            postLikeMapper.removeLike(accountId,postId);
        } catch (Exception e) {
            throw new GlobalException(1001,"取消点赞失败");
        }
    }

    @Override
    public void addCommentLike(Integer accountId, Integer commentId) {
        try {
            commentLikeMapper.addLike(accountId,commentId);
        } catch (Exception e) {
            throw new GlobalException(1001,"点赞失败");
        }
    }

    @Override
    public void removeCommentLike(Integer accountId, Integer commentId) {
        try {
            commentLikeMapper.removeLike(accountId,commentId);
        } catch (Exception e) {
            throw new GlobalException(1001,"取消点赞失败");
        }
    }

    @Override
    public Integer getLikeCountByPostId(Integer postId) {
        try {
            return postLikeMapper.countPostLikeByPostId(postId);
        } catch (Exception e) {
            throw new GlobalException(1001,"获取点赞数失败");
        }
    }
}
